/*
 * @(#)MulticastClient.java	1.0 Mar 8, 2008
 *
 *	The MIT License
 *
 *	Copyright (c) 2008 Malachi de AElfweald <malachid@gmail.com>
 *
 *	Permission is hereby granted, free of charge, to any person obtaining a copy
 *	of this software and associated documentation files (the "Software"), to deal
 *	in the Software without restriction, including without limitation the rights
 *	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 *	copies of the Software, and to permit persons to whom the Software is
 *	furnished to do so, subject to the following conditions:
 *
 *	The above copyright notice and this permission notice shall be included in
 *	all copies or substantial portions of the Software.
 *
 *	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 *	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 *	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 *	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 *	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 *	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 *	THE SOFTWARE.
 */
package org.eoti.net.mcast;

import static org.eoti.util.log.LogUtil.*;

import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.net.InetAddress;
import java.net.DatagramPacket;
import java.util.*;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ByteArrayInputStream;

public class MulticastClient<DATA>
extends Thread
{
	protected MulticastSocket socket;
	protected HashSet<MulticastListener<DATA>> listeners;
	protected boolean done = false;
	protected Multicast mcast;

	public MulticastClient()
	throws UnknownHostException
	{
		super("MulticastClient");
		mcast = new Multicast();
		listeners = new HashSet<MulticastListener<DATA>>();
		start();
	}

	public MulticastClient(Multicast mcast)
	{
		super("MulticastClient");
		this.mcast = mcast;
		listeners = new HashSet<MulticastListener<DATA>>();
		start();
	}

	public void close(){done = true;}
	public void register(MulticastListener<DATA> listener){listeners.add(listener);}
	public void unregister(MulticastListener<DATA> listener){listeners.remove(listener);}

	public void notifyListeners(MulticastEvent<DATA> event)
	{
		for(MulticastListener<DATA> listener : listeners)
			listener.multicastReceived(event);
	}

	public void run()
	{
		try{
	    	socket = new MulticastSocket(mcast.getPort());
	    	InetAddress group = mcast.getGroupAddress();
	    	int maxPS = mcast.getMaxPacketSize();
	    	socket.joinGroup(group);
	    	DatagramPacket packet;
	    	MulticastEvent<DATA> event;

	    	while(!done)
	    	{
	    		try{
			    	byte[] buf = new byte[maxPS];
			    	packet = new DatagramPacket(buf, buf.length);
			    	socket.receive(packet);
			    	event = readEvent(packet);
			    	event.addHop(packet.getAddress());
			    	notifyListeners(event);
			    }catch(Exception inner){
					throwing("Error", inner );
			    }
	    	}

			socket.leaveGroup(group);
			socket.close();
	    }catch(Exception e){
	    	throwing("Error", e);
	    }
	}

	protected MulticastEvent<DATA> readEvent(DatagramPacket packet)
	throws IOException, ClassNotFoundException
	{
		ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(packet.getData()));
		MulticastEvent<DATA> event = (MulticastEvent<DATA>)in.readObject();
		in.close();
		return event;
	}
}
